package com.shenghui.enterprise.interceptor;

import com.shenghui.enterprise.base.entity.BaseUser;
import com.shenghui.enterprise.contant.ConstantInfo;
import com.shenghui.enterprise.enterprise.entity.EntBasicInfo;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * @Description: 登录拦截器
 * @Author houjh
 * @Email: happyxiaohou@gmail.com
 * @Date: 2020-06-01 9:17
 * @Copyright (c) 2020-2022 云南昇晖科技有限公司
 */
public class LoginInterceptor implements HandlerInterceptor {
    
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
		HttpSession session = request.getSession();
		String url = request.getRequestURI();
		if(url.startsWith("/admin")){
			BaseUser sessionUser = (BaseUser) session.getAttribute(ConstantInfo.ADMIN_LOGIN_USER);
			if (StringUtils.isEmpty(sessionUser)) {
				response.reset();
				response.setCharacterEncoding("UTF-8");
				response.setContentType("application/json;charset=UTF-8");
				response.sendRedirect("/admin/login");
				return false;
			} else {
				return true;
			}
		} else if(url.startsWith("/front")) {
			EntBasicInfo entBasicInfo = (EntBasicInfo) session.getAttribute(ConstantInfo.FRONT_LOGIN_USER);
			if(StringUtils.isEmpty(entBasicInfo)){
				response.reset();
				response.setCharacterEncoding("UTF-8");
				response.setContentType("application/json;charset=UTF-8");
				response.sendRedirect("/");
				return false;
			} else {
				return true;
			}
		}else {
			return true;
		}
	}
	
	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
		String url = request.getRequestURI();
		System.out.println("先进入此方法："+url);
	}
 
	@Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception e) throws Exception {

    }

}
